package com.chatToolsRpc.handler;

import com.chatToolsRpc.message.RpcRequestMessage;
import com.chatToolsRpc.message.RpcResponseMessage;
import com.chatToolsRpc.server.service.HelloService;
import com.chatToolsRpc.server.service.ServiceFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author： pang-yun
 * @date： 2021-09-22 17:38
 * 功能目的 ：用于
 */
@ChannelHandler.Sharable
public class RpcRequestMessageHandler  extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) throws Exception {

        RpcResponseMessage response= new RpcResponseMessage();
        try {
            HelloService service = (HelloService) ServiceFactory.getService(Class.forName(msg.getInterfaceName()));
            Method method = service.getClass().getMethod(msg.getMethodName(), msg.getParameterType());
            Object invoke = method.invoke(service, msg.getParameterValue());
            response.setReturnValue(invoke);
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
            response.setExceptionValue(e);
        }
        ctx.writeAndFlush(response);

    }


    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        RpcRequestMessage rpcRequestMessage = new RpcRequestMessage(1,
                "com.chatToolsRpc.server.service.HelloService",
                "sayHello",
                String.class,
                new Class[]{String.class},
                new Object[]{"hello, world!"}
        );

        // 上述对象中  获取对象中的 接口类 全限定名
        Class<?> interfaceClazz = Class.forName(rpcRequestMessage.getInterfaceName());
        // 根据 接口类  获取 接口实现类
        HelloService service = (HelloService) ServiceFactory.getService(interfaceClazz);
        //根据方法名 和参数类型 确定具体方法
        Method method = service.getClass().getMethod(rpcRequestMessage.getMethodName(), rpcRequestMessage.getParameterType());
        // 根据具体方法 使用代理  执行方法
        Object invoke = method.invoke(service, rpcRequestMessage.getParameterValue());
        System.out.println(invoke);
    }



}
